<template>
  <!-- 登录页面 -->
  <div class="loginBox">
    <!-- 遮罩盒子 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 弹出框 -->
    <div class="login">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 登录选择方式 -->
      <section>
        <a
          href="javascript:;"
          :class="{ active: isShowPhone }"
          @click="isShowPhone = true"
          >手机登录</a
        >
        |
        <a href="javascript:;" :class="{ active: !isShowPhone }" @click="weChat"
          >微信登录</a
        >
      </section>
      <!-- 用户输入框 -->
      <div class="cont">
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="358"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgArr"
            ></slide-verify>
          </div>

          <div class="row code">
            <input
              type="text"
              name=""
              id=""
              placeholder="请输入短信验证码"
              class="inputLast"
              v-model="getMess"
            />
            <button @click="getCode" v-show="!isShowCount">获取验证码</button>
            <button v-show="isShowCount">{{ count }}</button>
          </div>
          <div class="row">
            <button class="btnLogin" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="weChatLogin" v-show="!isShowPhone" id="weChat"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils";
import { SendSMSAIP, PhoneReginAPI, BindingAPI } from "../request/api";
import { isShowToast } from "@/components/elementToast";

export default {
  data() {
    return {
      isShowPhone: true,
      isShowCode: true,
      phoneNumber: "",
      isShowCount: false,
      count: 6,
      msg: "向右滑动",
      getMess: "",
      imgArr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLoginModal: "loginModal/changeIsLoginModal",
      changeIsShowToastModal: "showToast/changeIsShowToastModal",
    }),
    ...mapActions({
      asyncChangeIsShowToastModal: "showToast/asyncChangeIsShowToastModal",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
      this.$refs.slideBlock.$refs.canvas.style.height = "0px";
      this.$refs.slideBlock.$refs.block.style.height = "0px";
      this.$refs.slideBlock.$el.children[2].style.height = "0px";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    async getCode() {
      // 校验手机号和滑块验证码
      if (!this.toVerify()) return;
      // 获取验证码

      let res = await SendSMSAIP({
        phone: this.phoneNumber,
      });

      // res为undefined
      // if (!res) return;

      // 验证码发送成功时启动倒计时
      if (res.code == 0) {
        // 页面倒计时
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            clearInterval(timer);
            this.count = 6;
            this.isShowCount = false;
          }
        }, 1000);
        // alert("验证码已发送！");
      } else {
        this.toast(res.message, "warning");
      }
    },
    // 弹窗
    toast(toastMsg, toastType) {
      // this.asyncChangeIsShowToastModal({
      //   flag: true,
      //   toastMsg,
      //   toastType,
      // });
      isShowToast(toastMsg, toastType);
    },

    // 校验手机号和滑块验证码
    toVerify() {
      // 验证手机号
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号！");

        this.toast("请输入正确的手机号！", "warning");

        return;
      }
      // 校验验证码
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请滑动验证码！");
        this.toast("请滑动验证码！", "warning");
        return;
      }
      return true;
    },
    // 登录按钮
    async submitFn() {
      // 校验手机号和滑块验证码
      if (!this.toVerify()) return;
      // 校验验证码是否为空
      if (this.getMess.trim() == "") {
        // alert("请输入短信验证码！");
        this.toast("请输入短信验证码！", "warning");
        return;
      }
      // 发起登录请求
      // 判断本地是否有uuid
      let res = null;
      let uuid = localStorage.getItem("uuid");
      if (uuid) {
        // 微信关联手机请求
        console.log("微信关联手机请求");
        res = await BindingAPI({
          verifyCode: this.getMess,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        // 正常手机号登录请求
        console.log("正常手机号登录请求");
        res = await PhoneReginAPI({
          verifyCode: this.getMess,
          phone: this.phoneNumber,
        });
      }

      if (!res) return;
      // alert(res.message);
      this.toast("登录成功！", "success");

      console.log("res:", res);

      // 存储token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);

      // 关闭登录窗口
      this.changeIsShowLoginModal(false);

      // 显示购物车图标
      this.changeIsLoginModal(true);

      // 清除本地uuid
      uuid && localStorage.removeItem("uuid");

      this.asyncChangeUserInfo();
      // let userInfo = await UserProfilesAIP();
      // console.log(userInfo);
    },
    // 显示微信二维码
    weChat() {
      this.isShowPhone = false;
      let _this = this;
      new WxLogin({
        id: "weChat",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3h7DQogICAgbWFyZ2luLXRvcDogMTBweDsNCn0NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.loginBox {
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: 999;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login {
    width: 555px;
    height: 423px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background: url("../assets/img/login-box-bg.png");
    .close {
      width: 22px;
      height: 22px;
      position: absolute;
      right: 60px;
      top: 15px;
      background-color: pink;
      background: url("../assets/img/close.png");
      cursor: pointer;
    }
    section {
      text-align: center;
      padding-top: 40px;
      color: #ccc;
      a {
        text-decoration: none;
        color: #ccc;
        &.active {
          color: #333;
        }
      }
    }
    .cont {
      width: 350px;
      margin: 10px auto;
      text-align: center;
      .phoneLogin {
        padding-top: 10px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        div:nth-child(2) {
          margin-bottom: 20px;
        }
        .row {
          flex: 1;
          width: 358px;
          input {
            width: 350px;
            height: 50px;
            text-indent: 1em;
            outline: none;
            &.inputCode {
              margin: 20px 0;
            }
          }
          .btnLogin {
            margin-top: 20px;
            width: 358px;
            height: 50px;
            cursor: pointer;
            border: none;
            background-color: #12358d;
            color: #fff;
          }
        }
        .code {
          width: 358px;
          display: flex;
          justify-content: space-between;
          input {
            width: 230px;
          }
          button {
            width: 100px;
            border: none;
            color: #fff;
            background-color: #12358d;
            cursor: pointer;
          }
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>>